package com.example.wan1.base.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.wan1.R;
import com.example.wan1.interfaces.RvScrollListener;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.MainActivity;
import com.example.wan1.widget.LoadingView;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.MaterialHeader;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/***
 * @Author: zxd
 * @CreateDate: 2020/6/22 9:44
 * @Description: 关于自定义布局的使用，可以直接嵌入到fragment的布局中
 * 直接使用自定义view，只好使用根布局，可以放到中间。使用fragment的布局不能放到中间
 *
 * 注意：一定要注意生命周期的顺序关系，否则动不动就出问题了
 *
 * 20200704 暂停使用inflateView，app体验太差
 * 20200706 改造成懒加载
 */
public abstract class RootFragment extends BaseMvpFragment {

    private LoadingView mLoadingView;
    private LinearLayout loadView;
    private View mRootView;
    private View errorView;
    private ViewGroup inflateView;
    private ViewGroup mContainer;

    //重复加载
    private TextView tvReload;

    protected Context mContext;
    protected Unbinder mUnbinder;

    protected abstract void initData();

    protected abstract void initView();

    protected abstract @LayoutRes
    int initLayoutRes();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = inflater.inflate(initLayoutRes(), container, false);
        mContainer = mRootView.findViewById(R.id.srl);
        if (mContainer != null) {
            MaterialHeader mSrlheader = mRootView.findViewById(R.id.srlheader);
            TypedValue typedValue = new TypedValue();
            getActivity().getTheme().resolveAttribute(R.attr.colorPrimary,
                    typedValue, true);
            mSrlheader.setColorSchemeResources(typedValue.resourceId);

            int color = ToolsUtils.getThemeColor(getActivity());
            if (color != 0) {
                mSrlheader.setColorSchemeColors(color);
                BallPulseFooter mFooter = mRootView.findViewById(R.id.srlfooter);
                if (mFooter != null) {
                    mFooter.setNormalColor(color);
                    mFooter.setAnimatingColor(color);
                }
            }
        }
        //项目页面继承自RootFragment，但是没有SmartRefreshLayout，只能这么弄
        if (mContainer == null) {
            mContainer = mRootView.findViewById(R.id.project_vp);
        }
        if (mContainer == null) {
            mContainer = mRootView.findViewById(R.id.nav_rv);
        }
        if (mContainer == null) {
            mContainer = mRootView.findViewById(R.id.website_fl);
        }

        mContainer.setVisibility(View.GONE);
        inflateView = (ViewGroup) mContainer.getParent();
        //initData();
        mUnbinder = ButterKnife.bind(this, mRootView);

        if (getActivity() instanceof MainActivity) {
            mRvScrollListener = (RvScrollListener) mContext;
        }
        //mRvScrollListener = (RvScrollListener) getActivity();
        initView();
        return mRootView;
    }

    public void showLoading() {
        showLoading("玩命加载中...");
    }

    public void showLoading(String msg) {
        View mLoadLayout = LayoutInflater.from(mContext).inflate(R.layout.loading_view, inflateView, true);
        mLoadingView = mLoadLayout.findViewById(R.id.loading_view);
        loadView = mLoadLayout.findViewById(R.id.loading_layout);
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
            TextView shapeTv = mLoadingView.findViewById(R.id.shape_tv);
            shapeTv.setText(msg);
            mLoadingView.startFallAnimator();
        }
    }

    public void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            inflateView.removeView(loadView);
            mContainer.setVisibility(View.VISIBLE);
        }
    }

    public void showError() {
        mLoadingView.setVisibility(View.GONE);
        inflateView.removeView(loadView);
        //如果错误，填充错误的布局
        View mErrorLayout = LayoutInflater.from(mContext).inflate(R.layout.view_error, inflateView, true);
        errorView = mErrorLayout.findViewById(R.id.view_error);
        tvReload = errorView.findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(v -> reload());
    }

    /***
     * 重新加载
     * 相当于下拉刷新
     */
    public void reload() {
        errorView.setVisibility(View.GONE);
        inflateView.removeView(errorView);
    }

    @Override
    public void onDestroy() {
        if (mUnbinder != null)
            mUnbinder.unbind();
        super.onDestroy();
    }

    private boolean isLoaded = false;
    private boolean isFirst = true;

    @Override
    public void onResume() {
        super.onResume();
        //Log.i("zxd", "onResume:root= " + isLoaded);
        if (!isLoaded && getUserVisibleHint() && isFirst) {
            initData();
            isLoaded = true;
            isFirst = false;//如果这里的fragment的适配器是FragmentStatePagerAdapter，改成这个就不能加载了
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //Log.i("zxd", "onDestroyView: root");
        isLoaded = false;
    }

    //需要添加隐藏的方法
    protected RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            RecyclerView.LayoutManager layout = recyclerView.getLayoutManager();
            if (layout instanceof StaggeredGridLayoutManager) {
                //int spanCount = ((StaggeredGridLayoutManager) layout).getSpanCount();
                //findFirstCompletelyVisibleItemPositions 可以点进去看看
                int[] position = ((StaggeredGridLayoutManager) layout).findFirstCompletelyVisibleItemPositions(null);
                if (position[0] == 0) {
                    //如果position为0表示列表正处于顶部
                    mRvScrollListener.inTop(true, recyclerView);
                } else {
                    mRvScrollListener.inTop(false, recyclerView);
                }
                /*int[] viewsIds = ((StaggeredGridLayoutManager) layout).findFirstCompletelyVisibleItemPositions(null);
                RecyclerView.ViewHolder firstViewHolder = recyclerView.findViewHolderForLayoutPosition(viewsIds[0]);
                View itemView = firstViewHolder.itemView;*/
            } else if (layout instanceof LinearLayoutManager) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //得到当前列表第一个完全显示的item的position
                int position = layoutManager.findFirstCompletelyVisibleItemPosition();
                if (position == 0) {
                    //如果position为0表示列表正处于顶部
                    mRvScrollListener.inTop(true, recyclerView);
                } else {
                    mRvScrollListener.inTop(false, recyclerView);
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //判断滑动方向，recycleView item 上拉 下滑不同动画
            RecyclerView.Adapter mAdapter = recyclerView.getAdapter();
            if (dy > 0) {
                isUp = true;
            } else {
                isUp = false;
            }

            //过滤掉一些缓慢的滑动
            if (Math.abs(dy) > 10) {
                //滑动方向
                mRvScrollListener.scrollType(dy > 0);
            }
        }
    };

    private RvScrollListener mRvScrollListener;
    private boolean isUp;
}
